package com.liangxy.news.ui.main.profile;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.liangxy.news.R;
import com.liangxy.news.database.AppDatabase;
import com.liangxy.news.model.News;
import com.liangxy.news.model.User;
import com.liangxy.news.ui.auth.LoginActivity;
import com.liangxy.news.util.SharedPreferencesManager;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Profile fragment to display user information and history
 */
public class ProfileFragment extends Fragment {

    private static final String TAG = "ProfileFragment";

    private ImageView ivAvatar;
    private TextView tvUsername;
    private TextView tvPhone;
    private Button btnEditProfile;
    private Button btnLogout;
    private Button btnFollowedNews;
    private Button btnChangePassword;
    private Button btnCheckUpdate;
    private Button btnViewHistory;
    
    private SharedPreferencesManager preferencesManager;
    private ExecutorService executorService;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile_new, container, false);
        
        // Initialize components
        ivAvatar = view.findViewById(R.id.ivAvatar);
        tvUsername = view.findViewById(R.id.tvUsername);
        tvPhone = view.findViewById(R.id.tvPhone);
        btnEditProfile = view.findViewById(R.id.btnEditProfile);
        btnLogout = view.findViewById(R.id.btnLogout);
        btnFollowedNews = view.findViewById(R.id.btnFollowedNews);
        btnChangePassword = view.findViewById(R.id.btnChangePassword);
        btnCheckUpdate = view.findViewById(R.id.btnCheckUpdate);
        btnViewHistory = view.findViewById(R.id.btnViewHistory);
        
        preferencesManager = new SharedPreferencesManager(requireContext());
        executorService = Executors.newSingleThreadExecutor();
        
        return view;
    }
    
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        
        // Load user information
        loadUserInfo();
        
        // Setup button listeners
        setupListeners();
    }
    
    /**
     * Load user information from shared preferences
     */
    private void loadUserInfo() {
        User user = preferencesManager.getUser();
        
        if (user != null) {
            Log.d(TAG, "Loading user info: " + user.getUsername());
            tvUsername.setText(user.getUsername());
            tvPhone.setText(user.getPhone());
            
            // Load avatar
            if (user.getAvatar() != null && !user.getAvatar().isEmpty()) {
                Glide.with(this)
                        .load(user.getAvatar())
                        .placeholder(R.drawable.default_avatar)
                        .error(R.drawable.default_avatar)
                        .circleCrop()
                        .into(ivAvatar);
            } else {
                ivAvatar.setImageResource(R.drawable.default_avatar);
            }
        } else {
            Log.e(TAG, "User is null, redirecting to login");
            // If user is not logged in, redirect to login screen
            redirectToLogin();
        }
    }
    
    /**
     * Redirect to login screen
     */
    private void redirectToLogin() {
        if (getActivity() != null) {
            Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(requireContext(), LoginActivity.class));
            getActivity().finish();
        }
    }
    
    /**
     * Setup button listeners
     */
    private void setupListeners() {
        btnEditProfile.setOnClickListener(v -> {
            // TODO: Navigate to edit profile screen
            Toast.makeText(requireContext(), "编辑资料功能即将上线", Toast.LENGTH_SHORT).show();
        });
        
        btnLogout.setOnClickListener(v -> {
            // Clear user data and navigate to login screen
            Log.d(TAG, "Logging out user");
            preferencesManager.clearUser();
            redirectToLogin();
        });
        
        btnFollowedNews.setOnClickListener(v -> {
            // 导航到关注的新闻页面
            navigateToFollowedNews();
        });
        
        btnChangePassword.setOnClickListener(v -> {
            // 导航到修改密码页面
            navigateToChangePassword();
        });
        
        btnCheckUpdate.setOnClickListener(v -> {
            // 检查应用更新
            checkAppUpdate();
        });
        
        btnViewHistory.setOnClickListener(v -> {
            // 导航到浏览历史页面
            navigateToHistory();
        });
    }
    
    /**
     * 导航到关注的新闻页面
     */
    private void navigateToFollowedNews() {
        try {
            User user = preferencesManager.getUser();
            if (user == null) {
                Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (!isAdded() || getActivity() == null) {
                Log.e(TAG, "Fragment not attached, cannot navigate to followed news");
                return;
            }
            
            // 先保存当前Fragment的状态
            getActivity().getSupportFragmentManager().saveFragmentInstanceState(this);

            try {
                // 创建并显示关注的新闻Fragment
                FollowedNewsFragment fragment = FollowedNewsFragment.newInstance(user.getId());
                getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentContainer, fragment)
                    .addToBackStack("profile")
                    .commitAllowingStateLoss();
                Log.d(TAG, "导航至我的关注页面");
            } catch (Exception e) {
                Log.e(TAG, "替换Fragment时出错: " + e.getMessage(), e);
                Toast.makeText(requireContext(), "导航失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "导航到我的关注页面时出错: " + e.getMessage(), e);
            Toast.makeText(requireContext(), "出现错误，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 导航到修改密码页面
     */
    private void navigateToChangePassword() {
        try {
            User user = preferencesManager.getUser();
            if (user == null) {
                Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (!isAdded() || getActivity() == null) {
                Log.e(TAG, "Fragment not attached, cannot navigate to change password");
                return;
            }
            
            // 先保存当前Fragment的状态
            getActivity().getSupportFragmentManager().saveFragmentInstanceState(this);

            try {
                // 创建并显示修改密码Fragment
                ChangePasswordFragment fragment = ChangePasswordFragment.newInstance(user.getId());
                getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentContainer, fragment)
                    .addToBackStack("profile")
                    .commitAllowingStateLoss();
                Log.d(TAG, "导航至修改密码页面");
            } catch (Exception e) {
                Log.e(TAG, "替换Fragment时出错: " + e.getMessage(), e);
                Toast.makeText(requireContext(), "导航失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "导航到修改密码页面时出错: " + e.getMessage(), e);
            Toast.makeText(requireContext(), "出现错误，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 检查应用更新
     */
    private void checkAppUpdate() {
        // 模拟检查更新
        Toast.makeText(requireContext(), "当前已是最新版本", Toast.LENGTH_SHORT).show();
    }
    
    /**
     * 导航到浏览历史页面
     */
    private void navigateToHistory() {
        try {
            User user = preferencesManager.getUser();
            if (user == null) {
                Toast.makeText(requireContext(), "请先登录", Toast.LENGTH_SHORT).show();
                return;
            }
            
            if (!isAdded() || getActivity() == null) {
                Log.e(TAG, "Fragment not attached, cannot navigate to history");
                return;
            }
            
            // 先保存当前Fragment的状态
            getActivity().getSupportFragmentManager().saveFragmentInstanceState(this);

            try {
                // 创建并显示浏览历史Fragment
                HistoryFragment fragment = HistoryFragment.newInstance(user.getId());
                getActivity().getSupportFragmentManager()
                    .beginTransaction()
                    .replace(R.id.fragmentContainer, fragment)
                    .addToBackStack("profile")
                    .commitAllowingStateLoss();
                Log.d(TAG, "导航至浏览历史页面");
            } catch (Exception e) {
                Log.e(TAG, "替换Fragment时出错: " + e.getMessage(), e);
                Toast.makeText(requireContext(), "导航失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "导航到浏览历史页面时出错: " + e.getMessage(), e);
            Toast.makeText(requireContext(), "出现错误，请稍后重试", Toast.LENGTH_SHORT).show();
        }
    }
    
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (executorService != null) {
            executorService.shutdown();
        }
    }
} 